package com.orange.api.filter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import server.rest.HttpContext;
import server.rest.ResponseException;
import server.rest.filter.AbstractRSFFilter;
import server.rest.filter.PostFilter;
import common.ParamHelper;

public class PaginationFilter extends AbstractRSFFilter implements PostFilter
{

    public String getName()
    {
        return "Pagination";
    }

    Map<String, Object> cacheDataMap = new HashMap<String, Object>();

    public void doPostFilter(HttpContext context, Object... objects)
    {
        if (null != objects && objects.length >= 1)
        {
            int page, rows;
            try
            {
                page = ParamHelper.getOptionalQueryInt(context, ParamHelper.PADDING_PAGE, 1);
                rows = ParamHelper.getOptionalQueryInt(context, ParamHelper.PADDING_ROWS, 10);
                boolean isNeedTotal =
                                ParamHelper.getOptionalQueryBoolean(context, ParamHelper.PADDING_NEED_TOTAL, true);
                if (objects[0] instanceof Collection)
                {
                    Collection c = (Collection) objects[0];
                    int size = c.size();
                    int start = Math.min((page - 1) * rows, size);
                    int end = Math.min(page * rows, size);

                    List<Object> list = new ArrayList<Object>(c);
                    list = list.subList(start, end);

                    if(isNeedTotal)
                    {
                        Map<String, Object> pagination = new HashMap<String, Object>();
                        objects[0] = pagination;
                        pagination.put("data", list);
                        pagination.put("total", size);
                    }
                    else
                    {
                        objects[0] = list;
                    }
                }

            }
            catch (ResponseException e)
            {
                page = 1;
                rows = 10;
                e.printStackTrace();
            }

        }

    }

}
